package com.farm.controller;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.farm.entity.User;
import com.farm.entity.UserRole;
import com.farm.service.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    // Admin endpoints
    @GetMapping("/admin/users")
    public String listUsers(Model model) {
        try {
            List<User> farmers = userService.findByRole(UserRole.FARMER);
            List<User> employees = userService.findByRole(UserRole.EMPLOYEE);
            model.addAttribute("farmers", farmers);
            model.addAttribute("employees", employees);
            return "admin/users";
        } catch (Exception e) {
            // 记录错误
            e.printStackTrace();
            // 添加错误消息到模型
            model.addAttribute("error", "获取用户列表失败：" + e.getMessage());
            return "error/500";
        }
    }

    @GetMapping("/admin/users/pending")
    public String listPendingUsers(Model model) {
        List<User> pendingFarmers = userService.findPendingFarmers();
        model.addAttribute("pendingFarmers", pendingFarmers);
        return "admin/pending-users";
    }

    @PostMapping("/admin/users/{userId}/approve")
    @ResponseBody
    public String approveUser(@PathVariable Long userId) {
        userService.approveUser(userId);
        return "success";
    }

    @PostMapping("/admin/users/employee")
    public String createEmployee(@ModelAttribute User user) {
        user.setRole(UserRole.EMPLOYEE);
        user.setApproved(true);
        userService.registerUser(user);
        return "redirect:/admin/users";
    }

    @PostMapping("/admin/users/{userId}/recharge")
    @ResponseBody
    public String rechargeBalance(@PathVariable Long userId, @RequestParam BigDecimal amount) {
        userService.rechargeBalance(userId, amount);
        return "success";
    }

    @PostMapping("/admin/users/recharge-all")
    @ResponseBody
    public String rechargeAllEmployees(@RequestParam BigDecimal amount) {
        userService.rechargeAllEmployees(amount);
        return "success";
    }

    @GetMapping("/admin/users/{userId}")
    @ResponseBody
    public ResponseEntity<?> getUser(@PathVariable Long userId) {
        try {
            User user = userService.findById(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Error: " + e.getMessage());
        }
    }

    @PutMapping("/admin/users/{userId}")
    @ResponseBody
    public ResponseEntity<String> updateUser(@PathVariable Long userId, @RequestBody User user) {
        try {
            user.setId(userId);
            User updatedUser = userService.updateUser(user);
            if (updatedUser != null) {
                return ResponseEntity.ok("success");
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("error: Failed to update user");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("error: " + e.getMessage());
        }
    }

    @DeleteMapping("/admin/users/{userId}")
    @ResponseBody
    public ResponseEntity<String> deleteUser(@PathVariable Long userId) {
        try {
            userService.deleteUser(userId);
            return ResponseEntity.ok("success");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("error: " + e.getMessage());
        }
    }
}